<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\QueryException;

class ImportNames extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:import-names';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */

    public function handle()
    {
        $file_names = [
            '水.txt',
            '水2.txt',
            '木.txt',
            '木2.txt',
            '金_done.txt',
            'ai_水.txt',
            'ai_金.txt',
            'ai_木.txt',
        ];

        $chars = [
            Processor::$LAST_NAME,
        ];

        foreach ($file_names as $file_name) {
            $file = fopen(public_path($file_name), 'r');
            while (!feof($file)) {
                $line = fgets($file);
                if ($line != '') {
                    $arr = preg_match_all('/\p{Han}/u', $line, $matches)
                        ? $matches[0]
                        : [];
                    $chars = array_merge($chars, $arr);
                }
            }
        }

        $bar = $this->output->createProgressBar(count($chars));
        foreach ($chars as $char) {
            try {
                $res = DB::table('tasks')->insert(['char' => $char]);
                if ($res) {
                    $this->info("\t" . '插入' . $char . '成功!');
                } else {
                    $this->info("\t" . '插入' . $char . '失败!');
                }
            } catch (QueryException $e) {
                $this->info("\t" . '插入' . $char . '失败!');
            }

            $bar->advance();
        }
        $bar->finish();
    }
}
